package org.mosquitos;

import net.jxta.peergroup.PeerGroup;
import net.jxta.peergroup.PeerGroupFactory;
import net.jxta.discovery.DiscoveryService;
import net.jxta.exception.PeerGroupException;
import net.jxta.protocol.PeerAdvertisement;

public class PublishPeer {

	static PeerGroup myGroup = null; // my initial group
	private DiscoveryService discoSvc;
	static PeerGroup netPeerGroup = null;

	private void startJxta() {
		try {
			// create, and Start the default jxta NetPeerGroup
			netPeerGroup = PeerGroupFactory.newNetPeerGroup();
		} catch (PeerGroupException e) {
			// could not instantiate the group, print the stack and exit
			System.out.println("fatal error : group creation failure");
			e.printStackTrace();
			System.exit(1);
		}
		// Extract the discovery service from our peer group
		discoSvc = netPeerGroup.getDiscoveryService();
	}

	private void publishPeer() {
		PeerAdvertisement adv; // advertisement for the new group

		String peerName = netPeerGroup.getPeerName();
		String peerGroupName = netPeerGroup.getPeerGroupName();
		String peerID = netPeerGroup.getPeerID().toString();

		System.out.println("NOM DU GROUPE = " + netPeerGroup.getPeerGroupName());

		System.out.println("Name = " + peerName + " - GroupName = "
				+ netPeerGroup + " - Id = " + netPeerGroup);
		adv = netPeerGroup.getPeerAdvertisement();
		adv.setName("Jomper");
		System.out.println("ADV = " + adv.toString());

		System.out.println("Creating a new group advertisement");

		try {
			// publish this advertisement
			// (send out to other peers and rendezvous peer)
			discoSvc.remotePublish(adv);
			System.out.println("Peer published successfully.\n");
		} catch (Exception e) {
			System.out.println("Error publishing group advertisement");
			e.printStackTrace();
		}
	}

	public static void main(String args[]) {
			System.out.println("Starting PublishPeer Demo ....");
		PublishPeer myapp = new PublishPeer();
			System.out.println("Lancement de JXTA");
		myapp.startJxta();
			System.out.println("JXTA lanc?");
			System.out.println("=====================================");
			System.out.println("Publication du Peer");
		myapp.publishPeer();
			System.out.println("Peer publi?");
			System.out.println("FIN PROG");
			System.exit(0);
	}
}
